package cn.yunyichina.provider.pay.service.impl;

import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.pay.constant.ResponseEnum;
import cn.yunyichina.provider.pay.entity.PaymentSetting;
import cn.yunyichina.provider.pay.exception.PaySettingNotFoundException;
import cn.yunyichina.provider.pay.service.AppService;
import cn.yunyichina.provider.pay.service.BaseAppService;
import cn.yunyichina.utils.convert.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lullaby on 2016/10/17.
 */
@Service
public class AppServiceImpl extends BaseAppService implements AppService {

    private static final Logger logger = LoggerFactory.getLogger(AppServiceImpl.class);

    /**
     * 通过应用CODE和应用类型编码获取APPID
     *
     * @param data
     * @return
     */
    @Override
    public ResponseObject authAppIdentity(String data) {
        logger.info("AppServiceImpl.authAppIdentity.data -> {}", data);

        ResponseObject response = new ResponseObject();
        Map params = JsonUtils.parseObject(data, Map.class);

        if (params != null && checkAuthAppIdentityParameters(params)) {
            String appCode = (String) params.get("app_code");
            String orgCode = (String) params.get("org_code");
            String payCode = (String) params.get("pay_code");
            short payMode = (short) this.getPayModeByPayCode(payCode);
            logger.info("AppServiceImpl.authAppIdentity.payMode -> {}", payMode);

            try {
                PaymentSetting paymentSetting = this.getPaymentSetting(appCode, orgCode, payMode);
                Map<String, String> result = new HashMap<>(1);
                result.put("app_id", paymentSetting.getPayAppId());

                response.setResultObject(result);
            } catch (PaySettingNotFoundException e) {
                logger.error("AppServiceImpl.authAppIdentity.PaySettingNotFoundException", e);
                response.setResultCodeAndMessage(
                        ResponseEnum.PAY_SETTING_NOT_FOUND.getCode(),
                        ResponseEnum.PAY_SETTING_NOT_FOUND.getMessage()
                );
            }
        } else {
            response.setResultCodeAndMessage(
                    ResponseEnum.Common.INVALID.getCode(),
                    ResponseEnum.Common.INVALID.getMessage()
            );
        }

        return response;
    }

}
